<template>
  <div class="bg-style">
    <i-pageBody class="add_i-color">
      <div slot="page-main">
        <div class="container container-space container-space--vertical">
          <div class="container-space__child">
            <Form ref="form" :model="formdata" :label-width="100">
              <Row :gutter="20">
                <i-col :span="5">
                  <FormItem prop="custId" label="用户名称：">
                    <Select
                      v-model="formdata.custId"
                      placeholder="请选择用户名称"
                      style="100%"
                      clearable
                    >
                      <Option
                        :value="value"
                        v-for="({ label, value }, index) in options.custs"
                        :key="index"
                        >{{ label }}</Option
                      >
                    </Select>
                  </FormItem>
                </i-col>
                <i-col :span="5">
                  <FormItem prop="devid" label="设备名称：">
                    <Select
                      v-model="formdata.devid"
                      placeholder="请选择设备名称"
                      style="100%"
                      clearable
                    >
                      <Option
                        :value="value"
                        v-for="({ label, value }, index) in options.devs"
                        :key="index"
                        >{{ label }}</Option
                      >
                    </Select>
                  </FormItem>
                </i-col>
                <i-col :span="5">
                  <FormItem prop="devType" label="设备类型：">
                    <Select
                      v-model="formdata.devType"
                      placeholder="请选择设备类型"
                      style="100%"
                      clearable
                    >
                      <Option
                        :value="value"
                        v-for="({ label, value }, index) in options.devTypes"
                        :key="index"
                        >{{ label }}</Option
                      >
                    </Select>
                  </FormItem>
                </i-col>
                <i-col :span="5">
                  <FormItem prop="time" label="操作时间：">
                    <Date-picker
                      style="width:100%"
                      type="daterange"
                      placeholder="选择操作时间"
                      v-model="formdata.time"
                      clearable
                    ></Date-picker>
                  </FormItem>
                </i-col>
                <i-col :span="5">
                  <FormItem prop="optype" label="操作类型：">
                    <Select
                      v-model="formdata.optype"
                      placeholder="请选择操作类型"
                      style="100%"
                      clearable
                    >
                      <Option
                        :value="value"
                        v-for="({ label, value }, index) in options.optypes"
                        :key="index"
                        >{{ label }}</Option
                      >
                    </Select>
                  </FormItem>
                </i-col>
                <i-col :span="6">
                  <Button
                    type="primary"
                    @click="handleQuery"
                    :loading="loading.search"
                  >
                    查询
                  </Button>
                  <Button
                    type="default"
                    @click="handleReset"
                    :loading="loading.reset"
                  >
                    重置
                  </Button>
                </i-col>
                <i-col :span="13" class="container-align--right">
                  <Button
                    type="success"
                    @click="exportControlView"
                    :loading="loading.export"
                  >
                    导出
                  </Button>
                </i-col>
              </Row>
            </Form>
          </div>
          <div class="container-space__child">
            <Table
              :columns="columns"
              :data="nextData"
              border
              stripe
              :loading="tableLoading"
            ></Table>
          </div>
          <div class="container-space__child" v-show="nextData.length > 0">
            <div class="container-page">
              <PageHeader
                :total="formdata.total"
                :page-size="formdata.pageSize"
                :page="formdata.page"
              ></PageHeader>
              <Page
                :total="formdata.total"
                :page-size="formdata.pageSize"
                :current="formdata.page"
                @on-change="handlePage"
                show-sizer
                @on-page-size-change="handlePageSize"
              />
            </div>
          </div>
        </div>
      </div>
    </i-pageBody>
  </div>
</template>
<script>
import PageHeader from "../../components/page-header";
import { TABLE_COLUMNS, OPTYPE_OPTIONS, OPER_OPTIONS } from "./constants";
import {
  getControlViewCustId,
  getControlViewDevId,
  getControlViewDevType,
  getControlViewList,
  relieveControlView,
  implementControlView,
  exportControlView
} from "@/api/scada";
import moment from "moment";
export default {
  name: "warning",
  props: {},

  data() {
    const columns = [
      ...TABLE_COLUMNS,
      {
        title: "操作",
        width: 100,
        fixed: "right",
        align: "center",
        render: (h, params) => {
          const { row } = params;
          const { isImplement, isRelieve, opid } = row;
          let buttons = [];
          if (isImplement) {
            buttons.push([
              h(
                "Button",
                {
                  props: {
                    type: "warning",
                    size: "small",
                    loading:
                      this.loading.implement && opid === this.implement.opid
                  },
                  nativeOn: {
                    click: () => {
                      this.handleImplement(row);
                    }
                  }
                },
                "执行"
              )
            ]);
          }
          if (isRelieve) {
            buttons.push([
              h(
                "Button",
                {
                  props: {
                    type: "primary",
                    size: "small",
                    loading: this.loading.relieve && opid === this.relieve.opid
                  },
                  nativeOn: {
                    click: () => {
                      this.handleRelieve(row);
                    }
                  }
                },
                "解除"
              )
            ]);
          }
          return h("span", buttons);
        }
      }
    ];
    return {
      loading: {
        normal: false,
        search: false,
        reset: false,
        page: false,
        export: false
      },
      options: {
        custs: [],
        devs: [],
        devTypes: [],
        optypes: OPTYPE_OPTIONS
      },
      formdata: {
        custId: "",
        devid: "",
        devType: "",
        time: "",
        optype: "",
        page: 1,
        pageSize: 10,
        total: 0
      },
      columns,
      data: [],
      relieve: {
        opid: ""
      },
      implement: {
        opid: ""
      }
    };
  },
  computed: {
    tableLoading() {
      const {
        loading: { normal, search, reset, page }
      } = this;
      return normal || search || reset || page;
    },
    nextData() {
      const { data } = this;
      return data.map((element) => {
        const { optype, operstatus, controltime } = element;
        const { label: opLabel } =
          OPTYPE_OPTIONS.find((option) => option.value === optype) || {};
        const { label: operLabel } =
          OPER_OPTIONS.find((option) => option.value === operstatus) || {};
        const isImplement =
          ["1", "2"].includes(optype) && ["0"].includes(operstatus);
        const isRelieve =
          ["4"].includes(optype) &&
          ["0", "1", "2", "3"].includes(operstatus) &&
          +new Date() < +new Date(controltime);
        return {
          ...element,
          opLabel,
          operLabel,
          isImplement,
          isRelieve
        };
      });
    }
  },
  created() {},
  mounted() {
    this.getControlViewCustId();
    this.getControlViewDevType();
    this.getControlViewList();
  },
  watch: {
    "formdata.custId"() {
      this.formdata.devid = "";
      this.options.devs = [];
      if (this.formdata.custId) {
        this.getControlViewDevId();
      }
    }
  },
  methods: {
    handleQuery() {
      this.formdata.page = 1;
      this.getControlViewList("search");
    },
    handleReset() {
      this.$refs.form.resetFields();
      this.formdata.page = 1;
      this.getControlViewList("reset");
    },
    handlePage(page) {
      this.formdata.page = page;
      this.getControlViewList();
    },
    handlePageSize(pageSize) {
      this.formdata.pageSize = pageSize;
      this.getControlViewList();
    },
    handleRelieve(row) {
      this.loading.relieve = true;
      const { opid: opId } = row;
      this.relieve.opid = opId;
      relieveControlView({ opId })
        .then((ret) => {
          const { code, result } = ret;
          if (code === 200 && result === 1) {
            this.getControlViewList();
          } else {
            this.$Message.error("解除失败");
          }
        })
        .finally(() => {
          this.loading.relieve = false;
        });
    },
    handleImplement(row) {
      this.loading.implement = true;
      const { opid: opId } = row;
      this.relieve.implement = opId;
      implementControlView({ opId })
        .then((ret) => {
          const { code, result } = ret;
          if (code === 200 && result === 1) {
            this.getControlViewList();
          } else {
            this.$Message.error("执行失败");
          }
        })
        .finally(() => {
          this.loading.implement = false;
        });
    },
    getControlViewCustId() {
      getControlViewCustId().then((ret) => {
        const { code, result } = ret || {};
        if (code === 200) {
          this.options.custs = (result || []).map((element) => {
            const { custId, custName } = element;
            return {
              value: custId,
              label: custName
            };
          });
        }
      });
    },
    getControlViewDevId() {
      const custId = "2dd4c3a3944d3570946d4d5999c473d2"; //this.formdata.custId;
      getControlViewDevId({ custId }).then((ret) => {
        const { code, result } = ret || {};
        if (code === 200) {
          this.options.devs = (result || []).map((element) => {
            const { equipId, equipName } = element;
            return {
              value: equipId,
              label: equipName
            };
          });
        }
      });
    },
    getControlViewDevType() {
      getControlViewDevType().then((ret) => {
        const { code, result } = ret || {};
        if (code === 200) {
          this.options.devTypes = (result || []).map((element) => {
            const { equipTypeNo, equipTypeName } = element;
            return {
              value: equipTypeNo,
              label: equipTypeName
            };
          });
        }
      });
    },
    getControlViewList(loadingType = "normal") {
      this.loading[loadingType] = true;
      const {
        formdata: {
          custId,
          devType,
          devid,
          optype,
          time,
          page: pageNum,
          pageSize
        }
      } = this;
      let [begintime, endtime] = time;
      begintime = begintime ? moment(begintime).format("yyyy-MM-DD") : "";
      endtime = endtime ? moment(endtime).format("yyyy-MM-DD") : "";
      const params = {
        custId: "2dd4c3a3944d3570946d4d5999c473d2",
        devType,
        devid,
        optype,
        begintime,
        endtime,
        pageNum,
        pageSize
      };
      getControlViewList(params)
        .then((ret) => {
          const { code, result } = ret || {};
          if (code === 200) {
            const { totalNum, controlViewVo } = result || {};
            this.formdata.total = totalNum || 0;
            this.data = controlViewVo || [];
          }
        })
        .finally(() => {
          this.loading[loadingType] = false;
        });
    },
    exportControlView() {
      this.loading.export = true;
      const {
        formdata: { custId, devType, devid, optype, time }
      } = this;
      let [begintime, endtime] = time;
      begintime = begintime ? moment(begintime).format("yyyy-MM-DD") : "";
      endtime = endtime ? moment(endtime).format("yyyy-MM-DD") : "";
      const params = {
        custId,
        devType,
        devid,
        optype,
        begintime,
        endtime
      };
      exportControlView(params, "arraybuffer")
        .then((ret) => {
          const blob = new Blob([ret], { type: "application/vnd.ms-excel" });
          this.downLoad(blob, "控制列表");
        })
        .finally(() => {
          this.loading.export = false;
        });
    },
    downLoad(blob, name) {
      const url = URL.createObjectURL(blob);
      let a = document.createElement("a");
      a.download = name;
      a.style.display = "none";
      a.href = url;
      document.body.appendChild(a);
      a.click();
      a.remove();
    }
  },
  components: { PageHeader }
};
</script>
<style scoped lang="scss">
.bg-style {
  background: url(~@/assets/img/welcome.png) center no-repeat;
  background-size: contain;
  width: 100%;
  height: 100%;
}
.container {
  padding: 20px;
  height: 100%;
  overflow: auto;
}
.container-title {
  padding-left: 10px;
  font-size: 16px;
  color: #333;
  position: relative;
}
.container-title::before {
  content: "";
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  display: inline-block;
  width: 4px;
  height: 16px;
  background-color: #0893fd;
  line-height: 16px;
}

.container-space > .container-space__child:not(:last-child) {
  margin-right: 20px;
}
.container-space.container-space--vertical
  > .container-space__child:not(:last-child) {
  margin-bottom: 20px;
  margin-right: 0;
}
.container-space--inner {
  padding: 20px;
}

.container-align--center {
  text-align: center;
}
.container-align--right {
  text-align: right;
}
.container-page {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
<style>
.ivu-btn-ghost {
  color: #fff;
  background: transparent;
}
</style>
<style lang="scss" scoped>
/deep/ .ivu-table-tip table tr td {
  text-align: center;
  background-image: url("~@/assets/img/zwsj.png");
  background-position: center 60px;
  background-repeat: no-repeat;
  color: #999;
  height: 369px;
  background-size: 190px;
  span {
    display: none;
  }
}
</style>
